package com.xpengplayer.update;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.google.gson.Gson;
import com.xpengplayer.BuildConfig;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 更新管理器
 * 负责检查服务器最新版本和处理应用更新
 */
public class UpdateManager {
    private static final String TAG = "UpdateManager";
    private static final String UPDATE_API_URL = "https://api.example.com/updates/latest";
    private static final String UPDATE_APK_DIR = "XpengPlayer/updates";
    private static final String UPDATE_APK_NAME = "XpengPlayer_update.apk";
    
    // 单例模式实现
    private static UpdateManager instance;
    
    private Context context;
    private OkHttpClient client;
    private Gson gson;
    private UpdateCallback updateCallback;
    private DownloadManager downloadManager;
    private long downloadId = -1;
    private DownloadCompleteReceiver downloadReceiver;
    
    // 私有构造方法
    private UpdateManager(Context context) {
        this.context = context.getApplicationContext(); // 使用应用上下文避免内存泄漏
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        this.gson = new Gson();
        this.downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        this.downloadReceiver = new DownloadCompleteReceiver();
    }
    
    // 静态getInstance方法，实现单例模式
    public static synchronized UpdateManager getInstance(Context context) {
        if (instance == null) {
            instance = new UpdateManager(context);
        }
        return instance;
    }
    
    public interface UpdateCallback {
        void onUpdateAvailable(UpdateInfo updateInfo);
        void onNoUpdate();
        // 添加与Activity中使用的方法名匹配的新方法
        default void onUpdateNotAvailable() {
            // 默认实现调用原有的onNoUpdate方法，保持兼容性
            onNoUpdate();
        }
        void onError(String errorMessage);
        void onDownloadProgress(int progress, long downloadedSize, long totalSize);
        void onDownloadComplete(File apkFile);
        void onDownloadFailed(String errorMessage);
    }
    
    /**
     * 设置更新回调
     */
    public void setUpdateCallback(UpdateCallback callback) {
        this.updateCallback = callback;
    }
    
    /**
     * 检查服务器是否有新版本
     */
    public void checkForUpdates() {
        Request request = new Request.Builder()
                .url(UPDATE_API_URL)
                .build();
        
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "检查更新失败: " + e.getMessage());
                if (updateCallback != null) {
                    updateCallback.onError("网络连接失败，请检查网络设置");
                }
            }
            
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response.isSuccessful() && response.body() != null) {
                        String jsonResponse = response.body().string();
                        UpdateInfo updateInfo = gson.fromJson(jsonResponse, UpdateInfo.class);
                        
                        // 比较版本号
                          if (isNewerVersion(BuildConfig.VERSION_NAME, updateInfo.getVersionName())) {
                            if (updateCallback != null) {
                                updateCallback.onUpdateAvailable(updateInfo);
                            }
                        } else {
                            if (updateCallback != null) {
                            // 同时调用两个方法，确保兼容性
                            updateCallback.onNoUpdate();
                            updateCallback.onUpdateNotAvailable();
                        }
                        }
                    } else {
                        if (updateCallback != null) {
                            updateCallback.onError("服务器响应异常");
                        }
                    }
                } catch (Exception e) {
                    Log.e(TAG, "解析更新信息失败: " + e.getMessage());
                    if (updateCallback != null) {
                            updateCallback.onError("解析更新信息失败");
                        }
                }
            }
        });
    }
    
    /**
     * 检查是否是新版本
     * 支持多种版本号格式，如 x.y.z, x.y.z.build 等
     */
    private boolean isNewerVersion(String currentVersion, String newVersion) {
        if (currentVersion == null || newVersion == null) {
            Log.e(TAG, "版本号为空");
            return false;
        }
        
        try {
            // 移除版本号中的非数字部分，如 "v" 前缀
            String normalizedCurrent = normalizeVersion(currentVersion);
            String normalizedNew = normalizeVersion(newVersion);
            
            // 按点分割版本号部分
            String[] currentParts = normalizedCurrent.split("\\.");
            String[] newParts = normalizedNew.split("\\.");
            
            int maxLength = Math.max(currentParts.length, newParts.length);
            
            // 比较每一部分
            for (int i = 0; i < maxLength; i++) {
                // 如果某一方没有更多部分，则视为0
                int currentNum = (i < currentParts.length) ? Integer.parseInt(currentParts[i]) : 0;
                int newNum = (i < newParts.length) ? Integer.parseInt(newParts[i]) : 0;
                
                if (newNum > currentNum) {
                    return true; // 新版本更大
                } else if (newNum < currentNum) {
                    return false; // 新版本更小
                }
                // 如果相等，继续比较下一部分
            }
            
            // 所有部分都相等，不是新版本
            return false;
        } catch (NumberFormatException e) {
            Log.e(TAG, "版本号格式错误: " + e.getMessage());
            // 如果版本号格式错误，默认返回false
            return false;
        }
    }
    
    /**
     * 标准化版本号，移除前缀和后缀
     */
    private String normalizeVersion(String version) {
        // 移除常见前缀如 "v"、"V" 或 "Version "
        String normalized = version.replaceAll("^[vV]|^Version\\s*", "");
        
        // 移除后缀部分（如 -beta, -release 等）
        int dashIndex = normalized.indexOf('-');
        if (dashIndex != -1) {
            normalized = normalized.substring(0, dashIndex);
        }
        
        // 只保留数字和点
        normalized = normalized.replaceAll("[^\\d.]", "");
        
        return normalized;
    }
    
    /**
     * 比较版本号，判断是否为新版本（基于版本号代码）
     */
    private boolean isNewVersion(int newVersionCode) {
        return newVersionCode > BuildConfig.VERSION_CODE;
    }
    
    /**
     * 下载APK文件
     */
    public void downloadApk(String apkUrl) {
        try {
            // 创建下载请求
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
            request.setTitle("XpengPlayer 更新");
            request.setDescription("正在下载新版本...");
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            
            // 设置下载文件的MIME类型
            request.setMimeType("application/vnd.android.package-archive");
            
            // 设置下载路径
            File apkDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), UPDATE_APK_DIR);
            if (!apkDir.exists()) {
                apkDir.mkdirs();
            }
            
            File apkFile = new File(apkDir, UPDATE_APK_NAME);
            if (apkFile.exists()) {
                apkFile.delete();
            }
            
            request.setDestinationUri(Uri.fromFile(apkFile));
            
            // 如果是Android 6.0及以上，可以设置网络类型限制
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 可选：只在WiFi下下载
                // request.setRequiresNetworkType(DownloadManager.Request.NETWORK_WIFI);
            }
            
            // 允许漫游下载
            request.setAllowedOverRoaming(false);
            
            // 获取下载管理器并开始下载
            if (downloadManager != null) {
                downloadId = downloadManager.enqueue(request);
                
                // 注册下载完成广播接收器
                context.registerReceiver(downloadReceiver, 
                        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                
                // 启动进度监控
                startProgressMonitoring(apkFile);
                
                Toast.makeText(context, "开始下载更新，请在通知栏查看下载进度", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "下载管理器不可用", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "下载APK失败: " + e.getMessage());
            Toast.makeText(context, "下载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            if (updateCallback != null) {
                    updateCallback.onDownloadFailed("下载失败: " + e.getMessage());
                }
        }
    }
    
    /**
     * 开始监控下载进度
     */
    private void startProgressMonitoring(final File apkFile) {
        final Handler handler = new Handler(Looper.getMainLooper());
        final Runnable progressRunnable = new Runnable() {
            @Override
            public void run() {
                if (downloadId != -1) {
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(downloadId);
                    
                    Cursor cursor = downloadManager.query(query);
                    if (cursor != null && cursor.moveToFirst()) {
                        int statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                        int status = cursor.getInt(statusIndex);
                        
                        switch (status) {
                            case DownloadManager.STATUS_SUCCESSFUL:
                                // 下载成功
                                cursor.close();
                                if (updateCallback != null) {
                                    updateCallback.onDownloadComplete(apkFile);
                                }
                                return;
                                
                            case DownloadManager.STATUS_FAILED:
                                // 下载失败
                                int reasonIndex = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
                                int reason = cursor.getInt(reasonIndex);
                                cursor.close();
                                String errorMessage = "下载失败，错误代码: " + reason;
                                if (updateCallback != null) {
                                    updateCallback.onDownloadFailed(errorMessage);
                                }
                                return;
                                
                            case DownloadManager.STATUS_RUNNING:
                                // 正在下载，更新进度
                                int bytesDownloadedIndex = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                                int totalBytesIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                                
                                long bytesDownloaded = cursor.getLong(bytesDownloadedIndex);
                                long totalBytes = cursor.getLong(totalBytesIndex);
                                
                                int progress = 0;
                                if (totalBytes > 0) {
                                    progress = (int) (bytesDownloaded * 100 / totalBytes);
                                }
                                
                                // 更新UI
                                if (updateCallback != null) {
                                    updateCallback.onDownloadProgress(progress, bytesDownloaded, totalBytes);
                                }
                                break;
                                
                            case DownloadManager.STATUS_PAUSED:
                                // 下载暂停
                                break;
                                
                            case DownloadManager.STATUS_PENDING:
                                // 下载等待
                                break;
                        }
                        
                        cursor.close();
                        // 继续监控进度
                        handler.postDelayed(this, 1000);
                    } else {
                        // 下载已取消或完成
                        if (updateCallback != null) {
                                    updateCallback.onDownloadFailed("下载已取消");
                                }
                    }
                }
            }
        };
        
        // 启动监控
        handler.post(progressRunnable);
    }
    
    /**
     * 取消下载
     */
    public void cancelDownload() {
        if (downloadId != -1 && downloadManager != null) {
            downloadManager.remove(downloadId);
            downloadId = -1;
        }
        
        try {
            context.unregisterReceiver(downloadReceiver);
        } catch (IllegalArgumentException e) {
            // 如果接收器未注册，忽略异常
        }
    }
    
    /**
     * 安装APK文件
     */
    public void installApk(File apkFile) {
        try {
            // 检查是否有权限安装未知来源应用 (Android 8.0+)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    // 请求安装未知来源应用的权限
                    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                    intent.setData(Uri.parse("package:" + context.getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    Toast.makeText(context, "请允许安装未知来源应用以完成更新", Toast.LENGTH_LONG).show();
                    return;
                }
            }

            Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri apkUri;
            
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // Android 7.0及以上需要使用FileProvider
                try {
                    apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", apkFile);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } catch (Exception e) {
                    // 如果FileProvider不可用，尝试使用其他方式
                    Log.e(TAG, "FileProvider错误: " + e.getMessage());
                    // 在Android 10及以上，尝试使用不同的URI方案
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        // 使用content URI
                        apkUri = Uri.fromFile(apkFile);
                    } else {
                        // 回退到file URI
                        apkUri = Uri.fromFile(apkFile);
                    }
                }
            } else {
                apkUri = Uri.fromFile(apkFile);
            }
            
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "安装APK失败: " + e.getMessage());
            Toast.makeText(context, "安装失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            // 显示更详细的错误信息以便调试
            Log.e(TAG, "APK文件路径: " + apkFile.getAbsolutePath());
            Log.e(TAG, "APK文件存在: " + apkFile.exists());
            Log.e(TAG, "APK文件可读: " + apkFile.canRead());
        }
    }
    
    /**
     * 安装APK文件（无参数版本，用于兼容旧代码）
     */
    public void installApk() {
        try {
            // 获取默认的APK文件路径
            String apkFileName = "xpengplayer_update.apk";
            File apkFile = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), apkFileName);
            
            if (apkFile.exists() && apkFile.canRead()) {
                installApk(apkFile);
            } else {
                Toast.makeText(context, "未找到可安装的APK文件", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "APK文件不存在或不可读: " + apkFile.getAbsolutePath());
            }
        } catch (Exception e) {
            Log.e(TAG, "安装APK失败: " + e.getMessage());
            Toast.makeText(context, "安装失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 释放资源
     */
    public void release() {
        try {
            context.unregisterReceiver(downloadReceiver);
        } catch (IllegalArgumentException e) {
            // 如果接收器未注册，忽略异常
        }
    }
}